package com.bmadmin.controller.data;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.bmadmin.domain.Datagrid;
import com.bmadmin.domain.FileUpload;
import com.bmadmin.domain.NormalResult;
import com.bmadmin.domain.NoticeDomain;
import com.bmadmin.domain.SysUsersPOJO;
import com.bmadmin.service.FileService;
import com.bmadmin.util.BMUtil;
import com.bmadmin.util.Constants;
import com.bmadmin.util.Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@RestController
@RequestMapping("/data")
public class FileController {
	private Logger logger = LogManager.getLogger(this.getClass().getName());
	@Autowired
    FileService fileService;
	
    /**
     * 获取资料上传列表
     */
	@GetMapping("/getFileList")
    public Object getFileList(FileUpload fileUpload,Integer page,Integer limit) {
    	Datagrid result = new Datagrid();
    	Map map = new HashMap();
		map.put("type", fileUpload.getType());
		logger.info(fileUpload);//列表条件输出
		if(page==null){
			page = 1;
		}
		if(limit==null){
			limit = 1000;
		}
		PageHelper.startPage(page, limit);
		List<FileUpload> list = fileService.getFileList(map);
		PageInfo pagelist = new PageInfo(list);
		
		result.setCode(0);
        result.setMsg("success");
        result.setData(list);
        result.setCount(pagelist.getTotal());

        return result;
    }
	
    @PostMapping(value = "uploadfile")
    public NormalResult uploadfile(HttpSession session,MultipartFile file,String type)throws IOException {
        NormalResult result = new NormalResult();
        InputStream is = null;
        try {
            // 判断文件是否为空
            if (file == null) {
                result.setCode("9999");
                result.setMsg("文件不能为空！");
                return result;
            }
            
            // 判断文件是否为空
            if (type == null||type.equals("")) {
                result.setCode("9999");
                result.setMsg("资料类型不能为空！");
                return result;
            }

            // 获取文件名
            String fileName = file.getOriginalFilename();
            

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Date now = new Date();
            String time = sdf.format(now);
//            String pdf_location = "D:\\soft\\nginx\\html\\hzwgs\\file\\"+time+"";
            String pdf_location = "D:/soft/nginx/html/hzwgs/file/"+time+"";
//            String location = "D:/soft/nginx/html/hzwgs/file/"+time+"";
            logger.info("上传文件保存路径：" + pdf_location);
	        File filePath = new File(pdf_location);
	        if (! filePath.exists()) {
	            filePath.mkdirs();
	            logger.info("文件保存路径不存在，创建成功！");
	        }
	        BMUtil.getFile(file.getBytes(), pdf_location, fileName);
	        FileUpload fileUpload = new FileUpload();
	        fileUpload.setType(type);
	        fileUpload.setFilename(fileName);
	        fileUpload.setFilepath(pdf_location);
	        int res = fileService.SaveFile(fileUpload);
	        if(res>0){
	        	result.setCode("0000");
	            result.setMsg("上传成功");
	        }else{
	        	result.setCode("9999");
	            result.setMsg("上传失败");
	        }
            return result;
        } catch (Exception e) {
            result.setCode("9999");
            result.setMsg("文件上传异常！");
            logger.error(e);
            return result;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    is = null;
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * 文件删除
     */
    @PostMapping("/deleteFile")
    public NormalResult deleteFile(FileUpload fileUpload) {
    	String log = "上传文件删除>>>>>>>>>>>";
        NormalResult result = new NormalResult();
        if (BMUtil.isNullOrEmpty(fileUpload.getId())) {
            result.setCode("9999");
            result.setMsg("传入文件ID为空!");
            logger.info(log+"传入文件ID为空!");
            return result;
        }
    	Map map = new HashMap();
		map.put("id", fileUpload.getId());
        List<FileUpload> list = fileService.getFileList(map);
        if(list==null||list.size()==0){
        	result.setCode("9999");
            result.setMsg("无法找到对应的文件记录为空!");
            logger.info(log+"无法找到对应的文件记录为空!");
            return result;
        }
        fileUpload = (FileUpload)list.get(0);
        String filepath = fileUpload.getFilepath();
        logger.info("删除文件路径：" + filepath);
        Util.deleteDir(filepath);
        int retResult = fileService.deleteFile(fileUpload.getId());
        if(retResult>0){
    		result.setCode("0000");
            result.setMsg("删除成功！");
            logger.info(log+"删除成功！");
    	}else{
    		result.setCode("9999");
            result.setMsg("删除失败！");
            logger.info(log+"删除失败！");
    	}
    	return result;
    }
    
    
}
